package com.inspector.app.ui.chat.adapter;

import static com.example.commen.utile.CommonUtils.runOnUiThread;
import static com.hjq.http.EasyHttp.post;

import android.annotation.SuppressLint;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import com.inspector.app.R;
import com.inspector.app.ui.chat.HistoryTaskChatActivity;
import com.inspector.app.ui.chat.TaskChatActivity;
import com.inspector.app.ui.chat.entity.DataBean;
import com.inspector.app.ui.chat.entity.ReceiveMessagesEntity;
import com.inspector.app.ui.chat.holder.ItemAudioReceiveHolder;
import com.inspector.app.ui.chat.holder.ItemAudioSendHolder;
import com.inspector.app.ui.chat.holder.ItemBotReceiveHolder;
import com.inspector.app.ui.chat.holder.ItemBotSendHolder;
import com.inspector.app.ui.chat.holder.ItemFileReceiveHolder;
import com.inspector.app.ui.chat.holder.ItemFileSendHolder;
import com.inspector.app.ui.chat.holder.ItemImageReceiveHolder;
import com.inspector.app.ui.chat.holder.ItemImageSendHolder;
import com.inspector.app.ui.chat.holder.ItemTextReceiveHolder;
import com.inspector.app.ui.chat.holder.ItemTextSendHolder;
import com.inspector.app.ui.chat.holder.ItemVideoReceiveHolder;
import com.inspector.app.ui.chat.holder.ItemVideoSendHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class ChatAdapter extends RecyclerView.Adapter {
    private static final int TYPE_SEND_TEXT = 1;
    private static final int TYPE_RECEIVE_TEXT = 2;
    private static final int TYPE_SEND_IMAGE = 3;
    private static final int TYPE_RECEIVE_IMAGE = 4;
    private static final int TYPE_SEND_VIDEO = 5;
    private static final int TYPE_RECEIVE_VIDEO = 6;
    private static final int TYPE_SEND_FILE = 7;
    private static final int TYPE_RECEIVE_FILE = 8;
    private static final int TYPE_SEND_AUDIO = 9;
    private static final int TYPE_RECEIVE_AUDIO = 10;
    private static final int TYPE_SEND_BOT = 11;
    private static final int TYPE_RECEIVE_BOT = 12;


    private static final int SEND_TEXT = R.layout.item_text_send;//发送文字消息
    private static final int RECEIVE_TEXT = R.layout.item_text_receive;//接收文字消息
    private static final int SEND_IMAGE = R.layout.item_image_send;//发送图片消息
    private static final int RECEIVE_IMAGE = R.layout.item_image_receive;//接收图片消息
    private static final int SEND_VIDEO = R.layout.item_video_send;//发送视频消息
    private static final int RECEIVE_VIDEO = R.layout.item_video_receive;//接收视频消息
    private static final int SEND_FILE = R.layout.item_file_send;//发送文件消息
    private static final int RECEIVE_FILE = R.layout.item_file_receive;//接收文件消息
    private static final int RECEIVE_AUDIO = R.layout.item_audio_receive;//接收语音消息
    private static final int SEND_AUDIO = R.layout.item_audio_send;//发送语音消息
    private static final int SEND_BOT = R.layout.item_bot_send;//发送点
    private static final int RECEIVE_BOT = R.layout.item_bot_receive;
    private List<ReceiveMessagesEntity> mList = new ArrayList<>();

    private OnItemListener mListener;
    private LifecycleOwner lifecycleOwner;

    private LayoutInflater mInflater;
    private int indexToUpdate;

    public ChatAdapter(LifecycleOwner lifecycleOwner) {
        this.lifecycleOwner = lifecycleOwner;

    }


    public void setOnItemListener(OnItemListener listener) {
        this.mListener = listener;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setData(List<ReceiveMessagesEntity> dataList) {
        this.mList.clear();
        this.mList.addAll(dataList);
        Collections.reverse(mList);
        notifyDataSetChanged();
    }


    public void setUpdateMessage(ReceiveMessagesEntity data) {
        mList.add(0, data);
        notifyItemInserted(0);
    }

    public void setUpdateRevocationMessage(ReceiveMessagesEntity data) {
        if (data != null && !mList.isEmpty()) {
            indexToUpdate = -1;
            // 遍历列表，直接比较msgId的值
            for (int i = 0; i < mList.size(); i++) {
                ReceiveMessagesEntity entity = mList.get(i);
                if (entity.getMsgId() == data.getMsgId()) {
                    indexToUpdate = i;
                    break;
                }
            }
            if (indexToUpdate >= 0) {
                ReceiveMessagesEntity existingEntity = mList.get(indexToUpdate);
                existingEntity.settShow(1);
                notifyItemChanged(indexToUpdate);
            }
        }
    }


    public void setUpdateCallBackMessage(final ReceiveMessagesEntity data) {
        if (data != null && mList.size() > 0) {
            final String id = extractIdFromMessage(data.getMessage());
            if (TextUtils.isEmpty(id)) {
                return;
            }
            final int index = findIndexById(id);
            if (index != -1) {
                updateListAndNotify(index, data);
            } else {
                // 如果没有找到匹配项,暂时不处理
            }
        }
    }

    private String extractIdFromMessage(String message) {
        try {
            JSONObject jsonObject = new JSONObject(message);
            return jsonObject.getString("id");
        } catch (JSONException e) {
            Log.e("ChatAdapter", "解析JSON异常", e);
            return "";
        }
    }

    private int findIndexById(final String id) {
        for (int i = 0; i < mList.size(); i++) {
            ReceiveMessagesEntity entity = mList.get(i);
            if (id.equals(extractIdFromMessage(entity.getMessage()))) {
                return i;
            }
        }
        return -1;
    }

    private void updateListAndNotify(final int index, ReceiveMessagesEntity data) {
        try {
            runOnUiThread(() -> {
                mList.set(index, data);
                notifyItemChanged(index);
            });
        } catch (Exception e) {
            Log.e("ChatAdapter", "更新列表异常", e);
        }
    }

    public List<ReceiveMessagesEntity> getData() {
        return mList;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (mInflater == null) {
            mInflater = LayoutInflater.from(parent.getContext());
        }
        switch (viewType) {
            case TYPE_SEND_TEXT:
                return new ItemTextSendHolder(mInflater.inflate(SEND_TEXT, parent, false));
            case TYPE_RECEIVE_TEXT:
                return new ItemTextReceiveHolder(mInflater.inflate(RECEIVE_TEXT, parent, false));
            case TYPE_SEND_IMAGE:
                return new ItemImageSendHolder(mInflater.inflate(SEND_IMAGE, parent, false));
            case TYPE_RECEIVE_IMAGE:
                return new ItemImageReceiveHolder(mInflater.inflate(RECEIVE_IMAGE, parent, false));
            case TYPE_SEND_VIDEO:
                return new ItemVideoSendHolder(mInflater.inflate(SEND_VIDEO, parent, false));
            case TYPE_RECEIVE_VIDEO:
                return new ItemVideoReceiveHolder(mInflater.inflate(RECEIVE_VIDEO, parent, false));
            case TYPE_SEND_AUDIO:
                return new ItemAudioSendHolder(mInflater.inflate(SEND_AUDIO, parent, false));
            case TYPE_RECEIVE_AUDIO:
                return new ItemAudioReceiveHolder(mInflater.inflate(RECEIVE_AUDIO, parent, false));
            case TYPE_SEND_BOT:
                return new ItemBotSendHolder(mInflater.inflate(SEND_BOT, parent, false));
            case TYPE_RECEIVE_BOT:
                return new ItemBotReceiveHolder(mInflater.inflate(RECEIVE_BOT, parent, false));
            case TYPE_SEND_FILE:
                return new ItemFileSendHolder(mInflater.inflate(SEND_FILE, parent, false));
            case TYPE_RECEIVE_FILE:
                return new ItemFileReceiveHolder(mInflater.inflate(RECEIVE_FILE, parent, false));
        }
        return new ItemTextSendHolder(mInflater.inflate(SEND_TEXT, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ReceiveMessagesEntity historyMessageEntity = mList.get(position);
        switch (getItemViewType(position)) {
            case TYPE_SEND_TEXT:
                ItemTextSendHolder holder1 = (ItemTextSendHolder) holder;
                holder1.bind(historyMessageEntity);
                holder1.setOnItemListener(mListener, position);
                break;
            case TYPE_RECEIVE_TEXT:
                ItemTextReceiveHolder holder2 = (ItemTextReceiveHolder) holder;
                holder2.bind(historyMessageEntity);
                holder2.setOnItemListener(mListener, position);
                break;
            case TYPE_SEND_IMAGE:
                ItemImageSendHolder holder3 = (ItemImageSendHolder) holder;
                holder3.bind(historyMessageEntity);
                holder3.setOnItemListener(mListener, position);
                break;
            case TYPE_RECEIVE_IMAGE:
                ItemImageReceiveHolder holder4 = (ItemImageReceiveHolder) holder;
                holder4.bind(historyMessageEntity);
                holder4.setOnItemListener(mListener, position);
                break;
            case TYPE_SEND_VIDEO:
                ItemVideoSendHolder holder5 = (ItemVideoSendHolder) holder;
                holder5.bind(historyMessageEntity);
                holder5.setOnItemListener(mListener, position);
                break;
            case TYPE_RECEIVE_VIDEO:
                ItemVideoReceiveHolder holder6 = (ItemVideoReceiveHolder) holder;
                holder6.bind(historyMessageEntity);
                holder6.setOnItemListener(mListener, position);
                break;
            case TYPE_SEND_AUDIO:
                ItemAudioSendHolder holder7 = (ItemAudioSendHolder) holder;
                holder7.bind(historyMessageEntity);
                holder7.setOnItemListener(mListener, position);
                break;
            case TYPE_RECEIVE_AUDIO:
                ItemAudioReceiveHolder holder8 = (ItemAudioReceiveHolder) holder;
                holder8.bind(historyMessageEntity);
                holder8.setOnItemListener(mListener, position);
                break;
            case TYPE_SEND_BOT:
                ItemBotSendHolder holder9 = (ItemBotSendHolder) holder;
                holder9.bind(historyMessageEntity);
                holder9.setOnItemListener(mListener, position);
                break;
            case TYPE_RECEIVE_BOT:
                ItemBotReceiveHolder holder10 = (ItemBotReceiveHolder) holder;
                holder10.bind(historyMessageEntity);
                holder10.setOnItemListener(mListener, position);
                break;
            case TYPE_SEND_FILE:
                ItemFileSendHolder holder11 = (ItemFileSendHolder) holder;
                holder11.bind(historyMessageEntity);
                holder11.setOnItemListener(mListener, position);
                break;
            case TYPE_RECEIVE_FILE:
                ItemFileReceiveHolder holder12 = (ItemFileReceiveHolder) holder;
                holder12.bind(historyMessageEntity);
                holder12.setOnItemListener(mListener, position);
                break;
        }
    }


    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public int getItemViewType(int position) {
        boolean isSend = mList.get(position).getSendUserId() == TaskChatActivity.mSenderId
                || mList.get(position).getSendUserId() == HistoryTaskChatActivity.mSenderId;//判断是不是自己发送的消息

        switch (mList.get(position).getMsgDetail()) {
            case 1:
                return isSend ? TYPE_SEND_TEXT : TYPE_RECEIVE_TEXT;
            case 2:
                return isSend ? TYPE_SEND_IMAGE : TYPE_RECEIVE_IMAGE;
            case 3:
                return isSend ? TYPE_SEND_AUDIO : TYPE_RECEIVE_AUDIO;
            case 4:
                return isSend ? TYPE_SEND_VIDEO : TYPE_RECEIVE_VIDEO;
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
                return isSend ? TYPE_SEND_BOT : TYPE_RECEIVE_BOT;
            case 11:
                return isSend ? TYPE_SEND_FILE : TYPE_RECEIVE_FILE;
            default:
                return -1;
        }
    }

    public interface OnItemListener {
        void showImageListener(DataBean dataBean, int position);

        void showVideoListener(DataBean dataBean, int position);

        void showBotListener(String url, int position);

        void showFileListener(String url, int position);

        void startAudioListener(AnimationDrawable animation, String url, int position);

        void OnItemLongListener(ReceiveMessagesEntity entity, View view, int position);

        void OnItemResendListener(ReceiveMessagesEntity entity, String file, int position);
    }
}
